<template>
  <div class="page">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-read"></i> 课程管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="handle-del mr10"
          @click="delAllSelection"
          >批量删除</el-button
        >
        <el-select
          ref="college"
          clearable
          size="medium"
          v-model="query.college"
          value-key="college_id"
          placeholder="学院"
          @change="queryChange"
          @clear="queryClear"
          class="handle-select mr10"
        >
          <el-option
            v-for="item in colleges"
            :key="item.college_id"
            :label="item.college_name"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          ref="nature"
          clearable
          v-model="query.nature"
          value-key="nature_id"
          placeholder="课程类型"
          @change="queryChange"
          @clear="queryClear"
          class="handle-select mr10"
        >
          <el-option
            v-for="item in natures"
            :key="item.nature_id"
            :label="item.nature_name"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="query.name"
          placeholder="课程名"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
        <el-button
          type="success"
          class="btn-add"
          icon="el-icon-lx-add"
          @click="handleAdd"
          >新增</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="course_id"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="course_name" label="课程名" width="200"></el-table-column>
        <el-table-column label="课程类型" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.nature.nature_id == 1
                  ? 'danger'
                  : scope.row.nature.nature_id == 2
                  ? 'success'
                  : ''
              "
              >{{ scope.row.nature.nature_name }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="书籍封面" align="center" width="120">
          <template slot-scope="scope">
            <el-image
              class="table-td-thumb"
              :src="scope.row.image_url"
              :preview-src-list="[scope.row.image_url]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="credit" width="80" label="课程学分"></el-table-column>
        <el-table-column prop="period" width="80" label="课程学时"></el-table-column>
        <el-table-column
          prop="college.college_name"
          width="200"
          label="所属学院"
        ></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="course_content"
          label="课程介绍"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="sizes, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="10"
          :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
          :page-count="pageTotal"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog
      title="编辑"
      :visible.sync="editVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rule" label-width="80px">
        <el-form-item label="课程名" prop="course_name">
          <el-input v-model="form.course_name"></el-input>
        </el-form-item>
        <el-form-item label="课程类型">
          <el-select
            v-model="form.nature"
            value-key="nature_id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in natures"
              :key="item.nature_id"
              :label="item.nature_name"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程学分" prop="credit">
          <el-input v-model.number="form.credit" type="number"></el-input>
        </el-form-item>
        <el-form-item label="课程学时" prop="period">
          <el-input v-model.number="form.period" type="number"></el-input>
        </el-form-item>
        <el-form-item label="所属学院">
          <el-select
            v-model="form.college"
            value-key="college_id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in colleges"
              :key="item.college_id"
              :label="item.college_name"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="form.course_content" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="封面上传">
          <el-upload
            action=""
            list-type="picture-card"
            :class="{ hide: uploadVisible }"
            :limit="1"
            :file-list="fileList"
            :http-request="handleUpload"
            :on-preview="handlePictureCardPreview"
            :on-progress="handleProgress"
            :on-remove="handleRemove"
            :on-change="handleCoverChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog
      title="新增"
      :visible.sync="addVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="80px" :rules="rule">
        <el-form-item label="课程名" prop="course_name">
          <el-input v-model="form.course_name"></el-input>
        </el-form-item>
        <el-form-item label="课程类型">
          <el-select
            v-model="form.nature.nature_id"
            value-key="nature_id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in natures"
              :key="item.nature_id"
              :label="item.nature_name"
              :value="item.nature_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程学分" prop="credit">
          <el-input v-model.number="form.credit" type="number"></el-input>
        </el-form-item>
        <el-form-item label="课程学时" prop="period">
          <el-input v-model.number="form.period" type="number"></el-input>
        </el-form-item>
        <el-form-item label="所属学院">
          <el-select
            v-model="form.college.college_id"
            value-key="college_id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in colleges"
              :key="item.college_id"
              :label="item.college_name"
              :value="item.college_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input v-model="form.course_content" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="封面上传">
          <el-upload
            action=""
            list-type="picture-card"
            :class="{ hide: uploadVisible }"
            :limit="1"
            :http-request="handleUpload"
            :on-preview="handlePictureCardPreview"
            :on-progress="handleProgress"
            :on-remove="handleRemove"
            :on-change="handleCoverChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRequest } from "@/api/index";
import { postRequest } from "@/api/index";
import { handleUploadImg } from '@/utils/upload';

export default {
  name: "basetable",
  data() {
    return {
      query: {
        college: { college_id: 0, college_name: "请选择" },
        nature: { nature_id: 0, nature_name: "请选择" },
        major: { major_id: 0 },
        name: "",
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      multipleSelection: [],
      delList: [],
      natures: [],
      colleges: [],
      editVisible: false,
      addVisible: false,
      dialogVisible: false,
      uploadVisible: false,
      pageTotal: 1,
      // 预览图片url
      dialogImageUrl: "",
      // 默认图片url
      fileList: [],
      // 图片上传限制个数
      limitCount: 1,
      form: {
        nature: { nature_id: 1 },
        college: { college_id: 1 }
      },
      idx: -1,
      id: -1,
      rule: {
        course_name: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        credit: [
          { required: true, message: "请输入课程学分!", trigger: "blur" }
        ],
        period: [
          { required: true, message: "请输入课程学时!", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getData();
    this.getNatures();
    this.getColleges();
  },
  mounted() {},
  methods: {
    // 获取 easy-mock 的模拟数据
    getData() {
      if (this.query.college.college_id || this.query.nature.nature_id) {
        this.queryChange(this.query.pageIndex);
      } else {
        getRequest("/public/course/getall", {
          itemsofpage: this.query.pageSize,
          current_page: this.query.pageIndex
        }).then(res => {
            if(res.code == 200) {
                this.tableData = res.data.courses;
                this.pageTotal = res.data.total_pages;
            }else {
                this.$message.error("获取课程信息失败!");
            }
        });
      }
    },
    searchData(name) {
        this.selectClear();
        getRequest("/public/course/getbyname", {
            course_name: this.query.name,
            itemsofpage: this.query.pageSize,
            current_page: this.query.pageIndex
        }).then(res => {
            if(res.code == 200) {
                this.tableData = res.data.courses;
                this.pageTotal = res.data.total_pages;
            }else {
                this.$message.error("获取课程信息失败!");
            }
        });
    },
    // 获取 全部课程类型
    getNatures() {
      getRequest("/public/course/getnature").then(res => {
        console.log(res);
        this.natures = res.data;
      });
    },
    // 获取 全部学院信息
    getColleges() {
      getRequest("/public/baseinfo/college/getall").then(res => {
        console.log(res);
        this.colleges = res.data;
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.searchData(this.query.name);
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          postRequest("/public/course/delete", { course_id: row.course_id }).then(
            res => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.tableData.splice(index, 1);
              }
            }
          );
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      const length = this.multipleSelection.length;
      let str = "";
      this.delList = this.delList.concat(this.multipleSelection);
      for (let i = 0; i < length; i++) {
        str += this.multipleSelection[i].name + " ";
      }
      this.$message.error(`删除了${str}`);
      this.multipleSelection = [];
    },
    handleProgress() {},
    // 编辑操作
    handleEdit(index, row) {
      this.initForm();
      this.idx = index;
      // 关闭上传文件按钮
      this.fileList = [];
      // 设置图片默认链接
      if (row.image_url) {
        this.uploadVisible = true;
        this.dialogImageUrl = row.image_url;
        this.fileList.push({ name: "cover", url: row.image_url });
      } else {
        // 如果图片不存在
        this.uploadVisible = false;
      }
      // 拷贝纯数据对象，否则会出现同步修改的状况
      this.form = JSON.parse(JSON.stringify(row));
      this.editVisible = true;
    },
    // 新增操作
    handleAdd() {
      this.initForm();
    //   this.fileList = [];
      this.uploadVisible = false;
      this.addVisible = true;
    },
    // 保存编辑
    saveEdit() {
      postRequest("/public/course/update", this.form).then(res => {
        if (res.code == 200) {
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.$set(this.tableData, this.idx, this.form);
        }
      });
      this.editVisible = false;
    },
    // 保存新增
    saveAdd() {
      postRequest("/public/course/save", this.form).then(res => {
        if (res.code == 200) {
          this.$message.success(`新增课程信息成功!`);
          this.getData();
        }
      });
      this.addVisible = false;
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
    //分页 Size
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getData();
    },
    handleRemove(file, fileList) {
      this.uploadVisible = fileList.length >= this.limitCount;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片方法
    handleUpload(item) {
      handleUploadImg(item).then(res => {
        if (res.code == 200) {
          this.$message.success("图片上传成功！");
          this.dialogImageUrl = res.data.url;
          this.form["image_url"] = res.data.url;
          this.uploadVisible = true;
        } else {
          this.$message.error("上传超出大小限制！");
        }
      });
    },
    handleCoverChange(file, fileList) {
      this.uploadVisible = fileList.length >= this.limitCount;
    },
    initForm() {
      this.form = { nature: { nature_id: 1 }, college: { college_id: 1 } };
    },
    // select查询变化时
    queryChange(index) {
      this.$set(this.query, "name", "");
      // 如果未传入，说明
      if(!index) {
          this.$set(this.query, "pageIndex", 1);
      }
      getRequest("/public/course/getbyunion", {
        college_id: this.query.college.college_id,
        major_id: this.query.major.major_id,
        nature_id: this.query.nature.nature_id,
        itemsofpage: this.query.pageSize,
        current_page: this.query.pageIndex
      }).then(res => {
        this.tableData = res.data.courses;
        this.pageTotal = res.data.total_pages;
      });
    },
    // select查询清空时
    queryClear() {
        if(!this.query.nature) {
            this.query.nature = {nature_id:0};
        }else if(!this.query.college) {
            this.query.college = {college_id:0};
        }
        this.getData();
    },
    // 使用name search时,清空select
    selectClear() {
        this.query.college = null;
        this.query.nature = null;
    }
  }
};
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.btn-add {
  float: right;
}

</style>
